#include "head_c.h"

int upload(const user_t* status, const portocol_t* portocol, int socket_fd)
{
    while(1){
        char file_name[60] = {0};

        strncpy(file_name, portocol->arg, sizeof(file_name) - 1);
        char* last_path = strrchr(file_name, '/');
        if(last_path != NULL){
            *last_path = '\0';
            mkdir(file_name, 0600);
            *last_path = '/';
        }

        int read_t = read(socket_fd, file_name, sizeof(file_name));
        if(read_t == -1){
            perror("read failed!\n");
            exit(1);
        }
        send(socket_fd, &read_t, sizeof(int), 0);
        send(socket_fd, file_name, read_t, 0);

        int file_fd = open(file_name, O_RDWR);
        if(file_fd == -1){
            perror("open failed!\n");
            exit(1);
        }

        struct stat st;
        if(fstat(file_fd, &st) == -1){
            perror("fstat failed!\n");
            exit(1);
        }
        send(socket_fd, &st.st_size, sizeof(off_t), MSG_NOSIGNAL);

        int send_fd = sendfile(socket_fd, file_fd, 0, st.st_size);
        if(send_fd == -1){
            perror("send failed!\n");
            exit(1);
        }
    }

    close(socket_fd);

    return 0;
}

